<?php
/**
 * 讨彩头活动
 */
namespace Api\Controller;

use Common\Controller\InterceptController;
use Common\Lib\Wxpay\Wxpay;

class TaocaitouController extends InterceptController
{
    private $cacheSendList = 'TaocaitouController' . 'sendList';
    private $cacheSendEnveList = 'TaocaitouController' . 'sendEnveList';
    private $cacheDetail = 'TaocaitouController' . 'detail';
    private $cacheDetailTwo = 'TaocaitouController' . 'detailTwo';

    //清除列表缓存
    private function clearCacheList($userId = 0)
    {
        S($this->cacheSendList . $userId, null);
        S($this->cacheSendEnveList . $userId, null);
    }

    //清除详情缓存
    private function clearCacheDetail($tctId = 0)
    {
        S($this->cacheDetail . $tctId, null);
        S($this->cacheDetailTwo . $tctId, null);
    }

    /**
     * 发出讨彩头列表
     * time 2018.01.30
     */
    public function sendList()
    {
        //获取缓存
        $cacheKey = $this->cacheSendList . $this->user_id;
        $cache    = S($cacheKey);
        if ($cache) {
            $this->ajaxReturn(['code' => 20000, 'msg' => 'success_cache', 'data' => $cache]);
        }
        //讨彩头信息
        $tct_list = M('Taocaitou')->where(['user_id' => $this->user_id])->order('update_time desc,id desc')->select();
        $data['total_num']    = 0;
        $data['total_amount'] = 0;
        $data['list']     = [];
        foreach ($tct_list as $value) {
            $data['list'][] = [
                'tct_id'   => $value['id'],
                'content'  => $value['content'],
                'remark'   => '你的好友正与参与集字大赛，助他一臂之力',
                'num_arr'  => $this->numArray($value),
                'num'      => $value['num'],
                'amount'   => $value['amount'],
                'add_time' => date('m-d H:i', $value['add_time']),
                'c_index'  => $this->wishIndex($value['content']),
            ];
            //汇总
            $data['total_num']    += $value['num'];
            $data['total_amount'] += $value['amount'];
        }
        $data['total_amount'] = number_format($data['total_amount'],2);
        //设置缓存
        S($cacheKey, $data, ['expire' => 180]);

        $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 发出红包列表
     * time 2018.01.30
     */
    public function sendEnveList()
    {
        //获取缓存
        $cacheKey = $this->cacheSendEnveList . $this->user_id;
        $cache    = S($cacheKey);
        if ($cache) {
            $this->ajaxReturn(['code' => 20000, 'msg' => 'success_cache', 'data' => $cache]);
        }
        //讨彩头信息
        $tct_list             = M('Enve')->where(['user_id' => $this->user_id, 'pay_status' => 'ok'])->order('id desc')->select();
        $data['total_num']    = 0;
        $data['total_amount'] = 0;
        $data['list']         = [];
        foreach ($tct_list as $value) {
            $content        = explode(',', $value['answer']);
            $data['list'][] = [
                'tct_id'       => $value['tct_id'],
                'pid'          => $value['id'],
                'to_user_name' => $value['to_user_name'],
                'content'      => $value['answer'],
                'quest'        => $value['quest'],
                'amount'       => $value['show_amount'],
                'add_time'     => date('m-d H:i', $value['add_time']),
                'c_index'      => $this->wishIndex($value['answer']),
                'q_index'      => (int)array_search($value['quest'], $content) + 1,
            ];
            //汇总
            $data['total_num']    += 1;
            $data['total_amount'] += $value['show_amount'];
        }
        $data['total_amount'] = number_format($data['total_amount'], 2);
        //设置缓存
        S($cacheKey, $data, ['expire' => 180]);

        $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 活动详情
     * time 2018.01.30
     */
    public function detail()
    {
        $tct_id = I('tct_id');
        if (!$tct_id) {
            $this->ajaxReturn(['code' => 40000, 'msg' => '参数错误']);
        }
        //获取缓存
        $cacheKey = $this->cacheDetail . $tct_id;
        $cache    = S($cacheKey);
        if ($cache) {
            $cache['tct_info']['is_self'] = $cache['tct_info']['user_id'] == $this->user_id ? 1 : 0;
            $cache['tct_info']['num_arr'] = $this->userNumArray($cache['tct_info'], $cache['list']);

            $this->ajaxReturn(['code' => 20000, 'msg' => 'success_cache', 'data' => $cache]);
        }
        //讨彩头信息
        $tct_info = M('Taocaitou')->where(['id' => $tct_id])->find();
        if (!$tct_info) {
            $this->ajaxReturn(['code' => 40000, 'msg' => '参数错误']);
        }
        //红包列表
        $hb_list = M('Enve')->field(['id', 'user_id','quest', 'user_name', 'show_amount', 'add_time', 'head_img'])
            ->where(['tct_id' => $tct_id, 'pay_status' => 'ok'])->select();
        $list    = [];
        foreach ($hb_list as $value) {
            $list[] = [
                'pid'       => $value['id'],
                'user_id'   => $value['user_id'],
                'quest'     => $value['quest'],
                'nick_name' => $value['user_name'],
                'head_img'  => $value['head_img'],
                'amount'    => $value['show_amount'],
                'add_time'  => date('m-d H:i', $tct_info['add_time']),
            ];
        }
        //返回
        $data = [
            'tct_info' => [
                'tct_id'    => $tct_info['id'],
                'user_id'   => $tct_info['user_id'],
                'num'       => $tct_info['num'],
                'amount'    => $tct_info['amount'],
                'nick_name' => $tct_info['nick_name'],
                'head_img'  => $tct_info['head_img'],
                'content'   => $tct_info['content'],
                'num_arr'   => $this->userNumArray($tct_info, $list),
                'remark'    => '你的好友正与参与集字大赛，助他一臂之力',
                'add_time'  => date('m-d H:i', $tct_info['add_time']),
                'is_self'   => $tct_info['user_id'] == $this->user_id ? 1 : 0,
                'c_index'   => $this->wishIndex($tct_info['content']),
            ],
            'list'     => $list,
        ];
        //设置缓存
        S($cacheKey, $data, ['expire' => 180]);

        $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 活动详情
     * time 2018.01.30
     */
    public function detailTwo()
    {
        $tct_id = I('tct_id');
        if (!$tct_id) {
            $this->ajaxReturn(['code' => 40000, 'msg' => '参数错误']);
        }
        //获取缓存
        $cacheKey = $this->cacheDetailTwo . $tct_id;
        $cache    = S($cacheKey);
        if ($cache) {
            if (isset($cache['tct_info'])) {
                $cache['tct_info']['is_self'] = $cache['tct_info']['user_id'] == $this->user_id ? 1 : 0;
            }
            $this->ajaxReturn(['code' => 20000, 'msg' => 'success_cache', 'data' => $cache]);
        }
        //讨彩头信息
        $tct_info = M('Taocaitou')->where(['id' => $tct_id])->find();
        if (!$tct_info) {
            $this->ajaxReturn(['code' => 40000, 'msg' => '参数错误']);
        }
        //红包列表
        $hb_list = M('Enve')->field(['id', 'user_id','quest', 'user_name', 'amount', 'add_time', 'head_img', 'show_amount'])
            ->where(['tct_id' => $tct_id, 'pay_status' => 'ok'])->select();
        $content = explode(',', $tct_info['content']);
        $list    = [];
        $num_arr = [0, 0, 0, 0];
        foreach ($hb_list as $value) {
            $key = (int)array_search($value['quest'], $content);
            //列表
            $list[$num_arr[$key]][$key] = [
                'pid'         => $value['id'],
                'user_id'     => $value['user_id'],
                'quest'       => $value['quest'],
                'nick_name'   => $value['user_name'],
                'head_img'    => $value['head_img'],
                'amount'      => $value['show_amount'],
                'show_amount' => '¥' . $value['show_amount'],
                'add_time'    => date('m-d H:i', $tct_info['add_time']),
            ];
            $num_arr[$key]++;
        }
        //组合数据
        foreach ($list as $key => $value) {
            $amount = 0;
            foreach ($num_arr as $k => $v) {
                if (!isset($list[$key][$k])) {
                    $list[$key][$k] = [
                        'pid'         => 0,
                        'user_id'     => 0,
                        'quest'       => '',
                        'nick_name'   => '',
                        'head_img'    => C('IMG_BASE_URL') . 'tx-bg.png',
                        'amount'      => '',
                        'show_amount' => '',
                        'add_time'    => '',
                    ];
                } else {
                    $amount += $list[$key][$k]['amount'];
                }
            }
            $list[$key][4] = [
                'pid'         => 0,
                'user_id'     => 0,
                'quest'       => '',
                'nick_name'   => '汇总',
                'head_img'    => '',
                'amount'      => number_format($amount, 2),
                'show_amount' => '',
                'add_time'    => '',
            ];

            $num_arr[$key]++;
        }
        //返回
        $data = [
            'tct_info' => [
                'tct_id'    => $tct_info['id'],
                'user_id'   => $tct_info['user_id'],
                'num'       => $tct_info['num'],
                'amount'    => $tct_info['amount'],
                'nick_name' => $tct_info['nick_name'],
                'head_img'  => $tct_info['head_img'],
                'content'   => $tct_info['content'],
                'num_arr'   => $this->numArray($tct_info),
                'remark'    => '你的好友正与参与集字大赛，助他一臂之力',
                'add_time'  => date('m-d H:i', $tct_info['add_time']),
                'is_self'   => $tct_info['user_id'] == $this->user_id ? 1 : 0,
                'c_index'   => $this->wishIndex($tct_info['content']),
            ],
            'list'     => $list,
        ];
        //设置缓存
        S($cacheKey, $data, ['expire' => 180]);

        $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 排行榜
     */
    public function rankList()
    {
        //获取缓存
        $cacheKey = 'TaocaitouController_rankList';
        $cache    = S($cacheKey);
        if ($cache) {
            $this->ajaxReturn(['code' => 20000, 'msg' => 'success_cache', 'data' => $cache]);
        }
        $list =M('WxUser')
            ->field(['id as user_id', 'nick_name', 'head_img', 'rank_num as total_num'])
            ->where('rank_num > 0 and status = 0')
            ->order('rank_num desc')
            ->limit(100)
            ->select();
        foreach ($list as $k => $v){
            $list[$k]['rand'] = $k+1;
        }
        $data['list'] = $list;
        //设置缓存
        S($cacheKey, $data, ['expire' => 120]);

        $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'data' => $data]);
    }

    /**
     * 创建活动
     * time 2018.01.30
     */
    public function create()
    {
        $content = I('post.content');
        $remark  = I('post.remark', '');
        $form_id = I('post.form_id', '');
        if (!$content) {
            $this->ajaxReturn(['code' => 40000, 'msg' => '内容不能为空']);
        }

        $data      = [
            'content'     => $content,
            'remark'      => $remark,
            'form_id'     => $form_id,
            'user_id'     => $this->user_id,
            'openid'      => $this->user_info['openid'],
            'nick_name'   => $this->user_info['nick_name'],
            'head_img'    => $this->user_info['head_img'],
            'update_time' => time(),
        ];
        $tct_model = M('Taocaitou');
        $where     = ['user_id' => $this->user_id, 'content' => $content];
        $info      = $tct_model->where($where)->find();
        if ($info) {
            $tct_model->where($where)->save($data);
            $ret = $info['id'];
        } else {
            $data['add_time'] = time();
            $ret              = $tct_model->add($data);
        }
        if (!$ret) {
            $this->ajaxReturn(['code' => 40000, 'msg' => '操作失败']);
        } else {
            //记录formid
            $this->recordFormid($form_id);
            //清除缓存
            $this->clearCacheList($this->user_id);
            $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'data' => ['tct_id' => (int)$ret]]);
        }
    }

    /**
     * 添加红包信息
     * time 2017.10.2
     */
    public function saveEnve()
    {
        if(isset($this->user_info['status']) && $this->user_info['status'] == 1){
            $this->ajaxReturn(['code' => 40000, 'msg' => '账号已被禁用']);
        }
        $post_data = I('post.');
        if (isset($post_data['pay_status'])) {
            unset($post_data['pay_status']);
        }
        $post_data['num']          = 1;
        $post_data['enve_type']    = 3;
        $post_data['is_adv']       = 0;
        $post_data['share2square'] = 0;
        $post_data['user_id']      = $this->user_id;
        $post_data['openid']       = $this->openid;
        $post_data['user_name']    = $this->user_info['user_name'];
        $post_data['head_img']     = $this->user_info['head_img'];
        //讨彩头id
        if (!isset($post_data['tct_id'])) {
            $this->ajaxReturn(['code' => 40000, 'msg' => '参数错误']);
        }
        $tct_id = (int)$post_data['tct_id'];
        //讨彩头信息
        $tct_model = M('Taocaitou');
        $tct_info  = $tct_model->where(['id' => $tct_id])->find();
        if (!$tct_info) {
            $this->ajaxReturn(['code' => 40000, 'msg' => '参数错误']);
        }
        $post_data['to_user_id']   = $tct_info['user_id'];
        $post_data['to_user_name'] = $tct_info['nick_name'];
        $post_data['answer']       = $tct_info['content'];
        $enveStr                   = str_replace(',', '', $tct_info['content']);
        //创建对象
        $enve_model = D("Enve");
        $wx_user    = M("WxUser");
        $post_data  = $enve_model->create($post_data);
        if (!$post_data) {
            $msg = $enve_model->getError() ?: '系统繁忙';
            $this->ajaxReturn(['code' => 40000, 'msg' => $msg]);
        }
        //红包金额
        $amount = sprintf("%.2f", $post_data['amount']);
        if ($amount <= 0) {
            $this->ajaxReturn(['code' => 40000, 'msg' => '红包金额不能为0']);
        }
        //开始事务
        M()->startTrans();
        /*查询用户余额*/
        $userAmount = $wx_user->field('amount,frozen_amount')->where(['id' => $this->user_id])->find();

        //减去被冻结的余额
        $userMoney = sprintf("%.2f", $userAmount['amount'] - $post_data['frozen_amount']);

        //减去用户余额
        $diffAmount = sprintf("%.2f", $userMoney - $amount);

        //解冻用户余额
        //$wx_user->where(['id' => $this->user_id])->setField(['frozen_amount' => 0]);
        //余额不足的情况
        $res_user = true;
        $log_data = [];
        if ($diffAmount < 0 || $userAmount['amount'] <= 0) {
            $wxpay        = new Wxpay();
            $out_trade_no = $post_data['out_trade_no'];
            //调起支付
            $pay    = [
                'body'         => '新年祝福-' . $enveStr,
                'out_trade_no' => $out_trade_no,
                'total_fee'    => abs($amount),
                'notify_url'   => "https://" . $_SERVER['HTTP_HOST'] . U('Api/Wxpay/OrderChange'),
            ];
            $respay = $wxpay->get_code($pay, $this->instance()->openid);
            $respay = json_decode($respay, true);
            //支付类型
            $respay['pay_type'] = 1;
            if ($userMoney > 0) {
                $respay['pay_type'] = 3;
            }
            // 冻结用户所有余额
            /*if ($userAmount['amount'] > 0) {
                $res_user = $wx_user->where(['id' => $this->user_id])->setField(['frozen_amount' => $userAmount['amount']]);
            }*/
            $log_data = [
                'pay_type'     => '1',
                'amount'       => $amount,
                'pay_status'   => 'ok',
                'desc'         => '微信支付',
                'action'       => __ACTION__,
                'content'      => json_encode($post_data, JSON_UNESCAPED_UNICODE),
                'add_time'     => time(),
                'type'         => 0,
                'out_trade_no' => $out_trade_no,
                'user_id'      => $this->user_id,
            ];
            //支付信息
            $respay['pay_type']     = $post_data['pay_type'] = 1;
            $post_data['prepay_id'] = trim(substr($respay['package'], strpos($respay['package'], '=') + 1));
            //unset($respay['prepay_id']);
        } elseif ($diffAmount >= 0) {
            //余额支付
            $res_user = $wx_user->where(['id' => $this->user_id])->setDec('amount', $amount); // 修改用户余额
            //插log
            $log_data = [
                'pay_type'   => '2',
                'amount'     => $amount,
                'pay_status' => 'ok',
                'desc'       => '余额支付',
                'action'     => __ACTION__,
                'content'    => json_encode($post_data, JSON_UNESCAPED_UNICODE),
                'add_time'   => time(),
                'user_id'    => $this->user_id,
            ];
            //支付信息
            $respay['pay_type']      = $post_data['pay_type'] = 2;
            $post_data['pay_status'] = 'ok';
            $post_data['prepay_id']  = $post_data['prepay_id'] ? $post_data['prepay_id'] : '';
        }
        if (!$res_user) {
            $enve_model->rollback();
            $this->ajaxReturn(['code' => 50000, 'msg' => '操作失败(user)']);
        }
        //红包入库
        $pid = $enve_model->add($post_data);
        if (!$pid) {
            $enve_model->rollback();
            $this->ajaxReturn(['code' => 50000, 'msg' => '操作失败(in)']);
        }
        //插入log
        $log_data['even_id'] = $pid;
        $res_log             = set_money_log($log_data, 'PayLog');
        if (!$res_log) {
            $enve_model->rollback();
            $this->ajaxReturn(['code' => 50000, 'msg' => '操作失败(log)']);
        }

        //提交事务
        M()->commit();
        //余额支付领取红包
        if ($log_data['pay_type'] == 2) {
            $enveInfo          = [
                'moneyList'  => [$post_data['amount']],
                'amount'     => $post_data['amount'],
                'receiveNum' => 0,
                'enveNum'    => $post_data['num'],
                'users'      => []
            ];
            $param             = $post_data;
            $param['tct_info'] = $tct_info;
            $rceiveData        = [
                'pid' => $pid
            ];
            $this->saveEnveReceive($param, $rceiveData, $enveInfo);
            //记录集字字数
            $this->incRankNum($tct_info,['user_id'=>$this->user_id,'quest'=>$post_data['quest']]);

        }

        //数据返回
        $respay['quest']     = $post_data['quest'];
        $respay['prepay_id'] = $post_data['prepay_id'];
        $respay['pid']       = $pid;
        $respay['tct_id']    = $post_data['tct_id'];

        //清除缓存
        $this->clearCacheList($this->user_id);
        $this->clearCacheList($tct_info['user_id']);
        $this->clearCacheDetail($tct_id);
        //记录formid
        if (isset($post_data['form_id']) && $post_data['form_id']) {
            $this->recordFormid($post_data['form_id']);
        }
        if (isset($post_data['prepay_id']) && $post_data['prepay_id']) {
            $this->recordFormid($post_data['prepay_id']);
            $this->recordFormid($post_data['prepay_id']);
            $this->recordFormid($post_data['prepay_id']);
        }

        $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'data' => $respay]);
    }

    /**
     * post 参数 前端获取到的respay中的package和pid
     * 前端确认是否支付成功，支付成功发送生成口令通知
     */
    public function sendCreateEnveNotify()
    {
        $this->ajaxReturn(['code' => 20000, 'msg' => 'success', 'data' => []]);
    }

    /**
     * 领取红包
     * time 2017.9.30
     */
    private function saveEnveReceive($param = [], $post_data = [], $enveInfo = [])
    {
        $tct_id = (int)$param['tct_id'];
        $pid    = (int)$post_data['pid'];
        //讨彩头信息
        $tct_model = M('Taocaitou');
        $tct_info  = $param['tct_info'];
        if (!$tct_info) {
            return false;
        }
        $post_data['tct_id']         = $tct_id;
        $post_data['receive_answer'] = $tct_info['content'];
        //用户id
        $userId     = (int)$tct_info['user_id'];
        $user_model = M('WxUser');
        $user       = $user_model->field(['id', 'nick_name', 'head_img'])->where(['id' => $userId])->find();
        //加入用户信息
        $post_data['user_id']   = $userId;
        $post_data['nick_name'] = $user['nick_name'];
        $post_data['head_img']  = $user['head_img'];
        //红包信息
        $enve_model = M("Enve");

        //检测是否领取过红包
        $enve_receive_model = D("EnveReceive");

        $enveInfo['amount']     = number_format($enveInfo['amount'] - $enveInfo['moneyList'][0], 2);
        $enveInfo['receiveNum'] = $enveInfo['receiveNum'] + 1;
        $receive_amount         = $enveInfo['moneyList'][0];
        array_splice($enveInfo['moneyList'], 0, 1);
        $enveInfo['users'][] = $userId;

        //插入领红包选项检测
        $post_data['receive_amount'] = $receive_amount;
        $post_data                   = $enve_receive_model->create($post_data);
        if (!$post_data) {
            return false;
        };

        //开始事务
        M()->startTrans();
        //更新红包数量和金额
        $data = ['amount' => $enveInfo['amount'], 'receive_num' => $enveInfo['receiveNum'], 'update_time' => time()];
        $res  = $enve_model->where('id=' . $pid . ' and del=0')->save($data);
        if (!$res) {
            $enve_model->rollback();

            return false;
        }

        //领取表入库
        $last_id = $enve_receive_model->add($post_data);
        if (!$last_id) {
            $enve_receive_model->rollback();

            return false;
        }

        //更新用户余额
        $res_user = $user_model->where(['id' => $userId])->setInc('amount', $receive_amount); // 增加money到余额
        if (!$res_user) {
            $user_model->rollback();

            return false;
        }

        //插log
        $log_data = [
            'pay_type'   => '1',
            'amount'     => $receive_amount,
            'pay_status' => 'ok',
            'desc'       => get_log_tpl('receive_enve'),
            'source'     => __ACTION__,
            'add_time'   => time(),
            'user_id'    => $userId,
            'enve_id'    => $pid,
        ];
        $res_log  = set_money_log($log_data);
        if (!$res_log) {
            M('MoneyLog')->rollback();

            return false;
        }
        //更新讨彩头数据
        $data          = [];
        $words         = $tct_info['words'] ? explode(',', $tct_info['words']) : [];
        $words[]       = $param['quest'];
        $data['words'] = implode(',', $words);
        $content       = explode(',', $tct_info['content']);
        $status        = true;
        foreach ($content as $v) {
            if (!in_array($v, $words)) {
                $status = false;
            }
        }
        if ($status) {
            $data['status'] = 2;
        }
        $res = $tct_model->where(['id' => $tct_id])->setInc('num', 1);
        if ($res) {
            $res = $tct_model->where(['id' => $tct_id])->setInc('amount', $receive_amount);
        }
        if ($res) {
            $res = $tct_model->where(['id' => $tct_id])->save($data);
        }
        if (!$res) {
            $tct_model->rollback();

            return false;
        }
        //提交事务
        M()->commit();

        return true;
    }

    /**
     * 增加排行榜集字数，每天每人每组每字记录一次
     */
    private function incRankNum($tct_info,$enve_info)
    {
        //增加排行榜集字数，每天每人每组每字记录一次
        $content        = explode(',', $tct_info['content']);
        $index        = (string)array_search($enve_info['quest'], $content);
        $cacheKeyRank = 'cacheIncRankNum:'.$tct_info['user_id'].date('Ymd').$enve_info['user_id'].$tct_info['id'].$index;
        if(!S($cacheKeyRank)){
            $Model = M();
            $sql = "UPDATE `hb_wx_user` SET `rank_num`=rank_num+1 WHERE `id` = ".$tct_info['user_id'];
            $ret = $Model->execute($sql);
        }
        S($cacheKeyRank,1, ['expire' => 86400]);

        return true;
    }

    /**
     * 统计每个字次数
     * @param $value
     * @return array
     */
    private function numArray($value)
    {
        $num_arr = [0, 0, 0, 0];
        $content = explode(',', $value['content']);
        $words   = explode(',', $value['words']);
        $words   = array_count_values($words);
        foreach ($content as $k => $v) {
            if (isset($words[$v])) {
                $num_arr[$k] = $words[$v];
            }
        }

        return $num_arr;
    }

    /**
     * 统计指定用户每个字次数
     */
    private function userNumArray($tct = [], $list = [])
    {
        $num_arr = [0, 0, 0, 0];
        $content = explode(',', $tct['content']);
        foreach ($list as $val) {
            foreach ($content as $k => $v) {
                if($tct['user_id'] == $this->user_id){
                    if ($val['quest'] == $v) {
                        $num_arr[$k] += 1;
                    }
                }else{
                    if ($val['quest'] == $v && $this->user_id == $val['user_id']) {
                        $num_arr[$k] += 1;
                    }
                }

            }
        }

        return $num_arr;
    }

    /**
     * 祝福语数组
     */
    private function wishIndex($quest = '')
    {
        $wishs = C('WISH_CONTENT');

        return (int)array_search($quest, $wishs);
    }

    /**
     * 保存formid
     * time 2018.01.30
     */
    public function saveFormid()
    {
        $formId = I('post.form_id');
        if (!$formId) {
            $this->ajaxReturn(['code' => 20000, 'msg' => '内容不能为空']);
        }
        //获取缓存
        $cacheKey = 'cacheSaveFormid' . date('Ymd') . $this->user_id;
        $cache    = S($cacheKey);
        if ($cache >= 5) {
            $this->ajaxReturn(['code' => 20000, 'msg' => 'success_cache']);
        }
        S($cacheKey, $cache + 1, ['expire' => 86400]);
        $this->recordFormid($formId);

        $this->ajaxReturn(['code' => 20000, 'msg' => 'success']);
    }

    /**
     * 保存formid
     * @param string $formId
     * @return mixed
     */
    private function recordFormid($formId = '')
    {
        $data = [
            'form_id'  => $formId,
            'user_id'  => $this->user_id,
            'openid'   => $this->user_info['openid'],
            'add_time' => time(),
        ];
        if ($formId) {
            $ret = M('UserFormid')->add($data);
        }

        return true;
    }
}

